package com.rain.shoppingscienceproj.ui.activity.order;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.rain.shoppingscienceproj.R;
import com.rain.shoppingscienceproj.http.BaseSubscriber;
import com.rain.shoppingscienceproj.http.ExceptionHandle;
import com.rain.shoppingscienceproj.http.RetrofitClient;
import com.rain.shoppingscienceproj.module.ImageData;
import com.rain.shoppingscienceproj.ui.activity.BaseActivity;
import com.rain.shoppingscienceproj.ui.activity.ImagePagerActivity;
import com.rain.shoppingscienceproj.ui.activity.setting.UserInfoActivity;
import com.rain.shoppingscienceproj.ui.adapter.ImageAdapter;
import com.rain.shoppingscienceproj.ui.base.GlobalData;
import com.rain.shoppingscienceproj.ui.utile.DeviceUtils;
import com.rain.shoppingscienceproj.ui.utile.TitleUtils;
import com.rain.shoppingscienceproj.ui.view.MyGridView;
import com.rain.shoppingscienceproj.utils.AppManager;
import com.rain.shoppingscienceproj.utils.ImageLoader;
import com.rain.shoppingscienceproj.utils.LoadingDialog;
import com.rain.shoppingscienceproj.utils.OssUtils;
import com.rain.shoppingscienceproj.utils.toast.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnItemClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import picker.prim.com.primpicker_core.PrimPicker;
import picker.prim.com.primpicker_core.entity.MimeType;

public class CommentActivity extends BaseActivity {


    private ImageAdapter adapter;
    private LinkedList<ImageData> imageList = new LinkedList<>();
    private LinkedList<ImageData> fistList = new LinkedList<>();
    private ImageData imageData = new ImageData(R.drawable.image_add, false);
    @BindView(R.id.et_comment)
    EditText et_comment;
    @BindView(R.id.gv_data)
    MyGridView gv_data;
    private String orderId = "", goodIds = "";
    @BindView(R.id.bar)
    ProgressBar bar;
    @BindView(R.id.textView)
    TextView textView;
    ImageView imageView;

    @OnItemClick(R.id.gv_data)
    void itemImage(int position) {
        ImageData data = (ImageData) adapter.getItem(position);
        if (data.isFile()) {
            if (imageList.contains(imageData))
                imageList.remove(imageData);
            ImagePagerActivity.ImageSize imageSize = new ImagePagerActivity.ImageSize(gv_data.getMeasuredWidth(), gv_data.getMeasuredHeight());
            ImagePagerActivity.startImagePagerActivity(this, imageList, position, imageSize);
            imageList.add(imageData);
        } else {
            PrimPicker
                    .with(this)
                    .choose(MimeType.ofImage())
                    .setSpanCount(Integer.parseInt(3 + ""))
                    .setMaxSelected(Integer.parseInt(9 + ""))
                    .setImageLoader(new ImageLoader())
                    .setShowSingleMediaType(true)
                    .setCapture(true)
                    .lastGo(1001);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1001 && resultCode == Activity.RESULT_OK) {
            List<String> pathlist = PrimPicker.obtainPathResult(data);
            if (pathlist != null && pathlist.size() != 0) {
                imageList.clear();
                for (String path : pathlist) {
                    File file = new File(path);
                    ImageData image = new ImageData(file, true);
                    image.setStrPath(pathlist.get(0));
                    imageList.add(image);
                }
                adapter.setImages(imageList);
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comment);
        userInfo = GlobalData.getUserInfo();
        AppManager.getAppManager().addActivity(this);
        ButterKnife.bind(this);
        TitleUtils.TitleRightText(this, "评论", "提交");
//        TitleUtils.mRightText.setTextColor(getResources().getColor(R.color.white));
        loadingDialog = new LoadingDialog(this, "正在加载...");
        goodIds = getIntent().getStringExtra("type");
//        goodIds = getIntent().getStringExtra("shopId");
        initData();
    }

    private void initData() {
        OssUtils.oss(this, imageView, bar, textView, 2);
        fistList.add(imageData);
        adapter = new ImageAdapter(this, fistList);
        gv_data.setAdapter(adapter);
    }

    @OnClick(R.id.rl_right)
    void save() {

        imageList.remove(imageData);

        String commentText = et_comment.getText().toString().trim();
        if (commentText.isEmpty()) {
            ToastUtils.showShortToast("请输入评论内容");
            return;
        }
        String deviceId = DeviceUtils.getUniqueId(this);
        String contextimg = "";
        for (int i = 0; i < imageList.size(); i++) {
            ImageData imageData = imageList.get(i);
            String pathName = deviceId + imageData.getFile().getName();
            OssUtils.setmService(pathName, imageData.getStrPath());
            contextimg += pathName + ",";
        }

        Map<String, String> map = new HashMap<>();
        map.put("token", userInfo.getToken());
        map.put("context", commentText);
        map.put("goodsId", goodIds);
        map.put("contextimg", contextimg);
        RetrofitClient.getInstance(this)
                .createBaseApi()
                .comment(map, new BaseSubscriber<ResponseBody>(this) {
                    @Override
                    public void onError(ExceptionHandle.ResponeThrowable e) {
                        ToastUtils.showShortToast("网络错误");
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        super.onNext(responseBody);
                        try {
                            String request = responseBody.string();
                            JSONObject json = new JSONObject(request);
                            int status = json.getInt("code");
                            if (status == 0) {
                                ToastUtils.showShortToast("评论成功");
                                finish();
                            } else {
                                ToastUtils.showShortToast(json.getString("message"));
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

}
